﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PKURG.CostSplit.Business;

public partial class Pages_AccountSplit : PageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadData();
            ddlApproation.DataBind();//提前绑定
            gvSplitDetailList.DataBind();
            SettingTBStyle();
        }

    }

    private void LoadData()
    {
        Guid id = Guid.Empty;
        string idString = Request["Id"];
        if (string.IsNullOrEmpty(idString) || !Guid.TryParse(idString, out id))
        {
            Common.GoErrorPage();
            return;
        }

        dynamic contractCostInfo = ContractCost.GetContractCostInfo(id);
        if (contractCostInfo == null)
        {
            Common.GoErrorPage();
            return;
        }

        this.lbProjectName.Text = contractCostInfo.ProjectName;
        this.lbStageName.Text = string.Format("{0}", contractCostInfo.StageName);
        this.lbAccountName.Text = contractCostInfo.AccountName;
        this.lbContract.Text = contractCostInfo.ContractName;
        this.lbScope.Text = contractCostInfo.Scope;
        if (string.IsNullOrEmpty(this.lbScope.Text))
        {
            this.lbScope.Text = "暂无";
        }
        if (string.IsNullOrEmpty(contractCostInfo.js_amount) || decimal.Parse(contractCostInfo.js_amount) == 0)
        {
            this.lbMoney.Text = ((decimal)(decimal.Parse(contractCostInfo.ht_amount) + decimal.Parse(contractCostInfo.sj_amount) + decimal.Parse(contractCostInfo.qs_amount)
                + decimal.Parse(contractCostInfo.bc_amount) + decimal.Parse(contractCostInfo.other_amount))).ToDisplayString();
        }
        else
            this.lbMoney.Text = ((decimal)(decimal.Parse(contractCostInfo.js_amount))).ToDisplayString();

        this.tbCause.Text = contractCostInfo.Reason;

        //if (contractCostInfo.IsCustom=="0")
        //{
        //    gvSplitDetailList.Enabled = false;
        //}

        //SetManualOrAuto(contractCostInfo.IsCustom);
        ViewState["IsCustom"] = contractCostInfo.IsCustom;

        //不控制
        //if (contractCostInfo.ApportionAreaType==0)
        //{
        //    ddlApproation.Enabled = true;
        //}
        //else
        //{
        //    ddlApproation.SelectedIndex = int.Parse(contractCostInfo.ApportionAreaType);
        //    ddlApproation.Enabled = false;
        //}


        hf_src.Value = contractCostInfo.AreaType.ToString();
        if (string.IsNullOrEmpty(contractCostInfo.ApportionAreaType) || contractCostInfo.ApportionAreaType == "0")
        {
            //还没有保存过，则选择科目的分摊原则值
            //ddlApproation.SelectedIndex = int.Parse(contractCostInfo.AreaType.ToString())-1;
            ddlApproation.SelectedValue = contractCostInfo.AreaType.ToString();
            ddlApproation.Enabled = false;
            cbIsCustomChecked.Checked = false;

        }
        else//使用已保存的分摊原则值
        {
            //ddlApproation.SelectedIndex = int.Parse(contractCostInfo.ApportionAreaType)-1;
            ddlApproation.SelectedValue = contractCostInfo.ApportionAreaType.ToString();
            ddlApproation.Enabled = true;
            cbIsCustomChecked.Checked = true;
        }
    }
    protected void ddlApproation_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvSplitDetailList.DataBind();
        Refresh();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        //先验证合同Id
        Guid id = Guid.Empty;
        string idString = Request["Id"];
        if (string.IsNullOrEmpty(idString) || !Guid.TryParse(idString, out id))
        {
            Common.GoErrorPage();
            return;
        }

        dynamic contractCostInfo = ContractCost.GetContractCostInfo(id);
        if (contractCostInfo == null)
        {
            Common.GoErrorPage();
            return;
        }
        //验证手动操作
        if (!VerifyManualData())
            return;
        //
        string reason = tbCause.Text;
        if (cbIsCustomChecked.Checked)
        {
            DetailSplit.UpdateContractCost(id, int.Parse(ddlApproation.SelectedItem.Value), 0, reason);
        }
        else
        {
            //取消自定义选择
            DetailSplit.UpdateContractCost(id, 0, 0, "");
        }
        //

        foreach (GridViewRow item in gvSplitDetailList.Rows)
        {
            CheckBox cb = item.FindControl("CBIsSelect") as CheckBox;
            TextBox lbCost = item.FindControl("lbCost") as TextBox;
            Label lbId = item.FindControl("lbId") as Label;
            if (cb.Checked)
            {
                decimal costValue = 0;
                decimal.TryParse(lbCost.Text, out costValue);

                DetailSplit.AddContractSplit(idString, lbId.Text, 0, costValue);
            }
            else
            {
                DetailSplit.DelContractSplit(idString, lbId.Text, 0);
            }
        }

        ScriptManager.RegisterClientScriptBlock(this, typeof(string), "1", "alert('保存完成')", true);
        //MessageBox.Show(this, typeof(Page), "alert('保存完成')");
    }

    private bool VerifyManualData()
    {
        if (ViewState["IsCustom"].ToString() == "1")
        {
            decimal total = decimal.Parse(lbMoney.Text);
            decimal gvCost = 0;
            foreach (GridViewRow item in gvSplitDetailList.Rows)
            {
                CheckBox cb = item.FindControl("CBIsSelect") as CheckBox;
                TextBox lbCost = item.FindControl("lbCost") as TextBox;
                if (cb.Checked)
                {
                    decimal costValue = 0;
                    decimal.TryParse(lbCost.Text, out costValue);
                    gvCost += costValue;
                }
            }
            if (total != gvCost)
            {
                ScriptManager.RegisterClientScriptBlock(this, typeof(string), "2", "alert('分摊值之和不等于总核算金额')", true);
                return false;
            }
        }
        return true;
    }

    public string GetShoundShowData(params Object[] areas)
    {
        //Object datas = {area_zd };
        if (ddlApproation.SelectedIndex >= 0)
        {
            return areas[ddlApproation.SelectedIndex].ToDisplayString();
        }
        return "";
    }
    protected void gvSplitDetailList_DataBound(object sender, EventArgs e)
    {
        //Refresh();
    }

    /// <summary>
    /// 1为手动，0为自动
    /// </summary>
    /// <param name="isManual"></param>
    private void SetManualOrAuto(string isManual)
    {
        foreach (GridViewRow item in gvSplitDetailList.Rows)
        {
            TextBox lbCost = item.FindControl("lbCost") as TextBox;
            //自动需处理，手动无需处理
            if (isManual == "0")
            {
                lbCost.ReadOnly = true;
                lbCost.CssClass = "label";
            }
        }
    }

    private void SettingTBStyle()
    {
        foreach (GridViewRow item in gvSplitDetailList.Rows)
        {
            TextBox lbCost = item.FindControl("lbCost") as TextBox;
            if (ViewState["IsCustom"].ToString() == "0")
            {
                lbCost.ReadOnly = true;
                lbCost.CssClass = "label";
            }
            else
            {
                lbCost.ReadOnly = false;
            }
        }
    }

    private void Refresh()
    {
        decimal sumArea = 0;
        foreach (GridViewRow item in gvSplitDetailList.Rows)
        {
            CheckBox cb = item.FindControl("CBIsSelect") as CheckBox;
            TextBox lbCost = item.FindControl("lbCost") as TextBox;

            //不管面积是否为空，先设置属性
            if (ViewState["IsCustom"].ToString() == "0")
            {
                lbCost.ReadOnly = true;
                lbCost.CssClass = "label";
            }
            else
            {
                lbCost.ReadOnly = false;
            }

            if (cb.Checked)
            {
                Label lbArea = item.FindControl("lbArea") as Label;
                if (string.IsNullOrEmpty(lbArea.Text))
                {
                    continue;
                }
                sumArea += decimal.Parse(lbArea.Text);
            }
            else
                lbCost.Text = "";


        }

        decimal totalCost = decimal.Parse(lbMoney.Text);
        foreach (GridViewRow item in gvSplitDetailList.Rows)
        {
            CheckBox cb = item.FindControl("CBIsSelect") as CheckBox;
            Label lbArea = item.FindControl("lbArea") as Label;
            TextBox lbCost = item.FindControl("lbCost") as TextBox;
            if (cb.Checked)
            {
                if (sumArea == 0)
                {
                    lbCost.Text = "0.00";
                }
                else
                {
                    lbCost.Text = (decimal.Parse(lbArea.Text) * totalCost / sumArea).ToDisplayString();

                }
            }
            else
            {
                lbCost.Text = "";
            }
        }
    }

    protected void CBIsSelect_CheckedChanged(object sender, EventArgs e)
    {
        ///自动才处理
        if (ViewState["IsCustom"].ToString() == "0")
        {
            Refresh();
        }
    }
    protected void cbIsCustomChecked_CheckedChanged(object sender, EventArgs e)
    {
        if (cbIsCustomChecked.Checked)
        {
            ddlApproation.Enabled = true;
        }
        else
        {
            ddlApproation.Enabled = false;
            ddlApproation.SelectedValue = hf_src.Value;
            gvSplitDetailList.DataBind();
            Refresh();
        }
    }
}